package com.sx.gongzhong.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sx.gongzhong.R;
import com.sx.gongzhong.activity.ImagePlayActivity;
import com.sx.gongzhong.activity.VideoPlayerActivity;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.voiceamr.Player;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.HashMap;
import java.util.List;

/**
 * Created by XZY on 2018/1/2.
 */

public class ImageAdapter extends CommonAdapter<PhotoBean> {

    private Player player;
    private Context context;

    public ImageAdapter(Context context, int layoutId, List<PhotoBean> datas) {
        super(context, layoutId, datas);
        this.context=context;
    }

    @Override
    protected void convert(ViewHolder viewHolder, final PhotoBean item, final int position) {
        final String type = item.getFileType();
        final ImageView imageView= viewHolder.getView(R.id.imageView);
        final TextView tvTime=viewHolder.getView(R.id.tv_Time);
        final FrameLayout ff=viewHolder.getView(R.id.ff);
        final RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.img_fail)
                .error(R.mipmap.img_fail);
        if ("video".equalsIgnoreCase(type)) {
            imageView.setImageResource(R.mipmap.img_video);
        }else if ("audio".equalsIgnoreCase(type)) {
            imageView.setVisibility(View.GONE);
            ff.setVisibility(View.VISIBLE);
            int dur = getRingDuring(ServiceFactory.getUrl( item.getPath()));
            tvTime.setText(dur+"");
            setWidth(ff, dur);
            tvTime.setVisibility(View.VISIBLE);

       } else {//图片
            Glide.with(context)
                    .load(ServiceFactory.getUrl(item.getPath()))
                    .apply(options)
                    .into(imageView);
        }
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("video".equalsIgnoreCase(type)) {
                    context.startActivity(new Intent(context,
                            VideoPlayerActivity.class).putExtra(
                            "path",ServiceFactory.getUrl( item.getPath())));
                }else {//图片
                    context.startActivity(new Intent(context, ImagePlayActivity.class).putExtra(
                            "path", ServiceFactory.getUrl(item.getPath()) ));
                }
            }
        });
        ff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("audio".equalsIgnoreCase(type)) {
                    int isPlayingPostion = -1;
                    for (int i = 0; i < getCount(); i++) {
                        if (getItem(i).isPlay) {
                            isPlayingPostion = i;
                            break;
                        }
                    }
                    if (player == null) {
                        player = new Player(context);
                    }
                    if (player.isPlay()){
                        player.stop();
                        getItem(isPlayingPostion).isPlay = false;
                        if (position!=isPlayingPostion){
                            playAudio(position);
                        }
                    }else {
                        getItem(position).isPlay = true;
                        playAudio(position);
                    }
                    notifyDataSetChanged();
                }
            }
        });
    }
    /**
     * 播放音频
     * @param position
     */
    private void playAudio(final int position){
        getItem(position).isPlay = true;
        player.playUrl( ServiceFactory.getUrl(getItem(position).getPath()), null, new Player.OnCompletionListener() {
            @Override
            public void onPlayComplet() {
                getItem(position).isPlay = false;
                notifyDataSetChanged();
            }
        });
    }

    private void setWidth(FrameLayout view,int width){
        ViewGroup.LayoutParams params= view.getLayoutParams();
        params.width=(int)(200*(1.0f*width/20)) + 60;
        view.setLayoutParams(params);
    }

    public int getRingDuring(String mUri){
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
        try {
            if (mUri != null) {
                HashMap<String, String> headers=null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            }
            String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
            int d = Integer.valueOf(duration) / 1000;
            if (d < 1){
                return 1;
            }else {
                return d ;
            }
        } catch (Exception ex) {
        } finally {
            mmr.release();
        }
        return 0;
    }
}
